import { _decorator, Component, Node, SpringJoint2D, Sprite, UITransform,Animation, AnimationClip, animation, SpriteFrame } from 'cc';
import { CONTROLLER_ENUM, DIRECTION_ENUM, DIRECTION_ORDER_ENUM, ENTITY_STATE_ENUM, ENTITY_TYPE_ENUM, EVENT_ENUM, PARAMS_NAME_ENUM } from '../Enums';


import { IEntity } from '../levels';
import { EntityManager } from './EntityManager';
import EventManager from '../Runtime/EventManger';
import DataManager from '../Runtime/DataManager';
const { ccclass, property } = _decorator;



@ccclass('EnemyManager')
export class EnemyManager extends EntityManager {
  // 初始化
  async init(params:IEntity) {
    // 3. 初始化状态机放外面
    // this.fsm = this.addComponent(WoodenSkeletonStateMachine)
    // await this.fsm.init(params)
    super.init(params)  // 调用父类初始化
    EventManager.Instance.on(EVENT_ENUM.PLAYER_BORN,this.onChangeDirection ,this)
    EventManager.Instance.on(EVENT_ENUM.PLAYER_MOVE_END,this.onChangeDirection ,this)
    EventManager.Instance.on(EVENT_ENUM.ATTACK_ENENY,this.onDead,this)
    this.onChangeDirection(true)
  }

  onDestroy(){
    super.onDestroy()
    EventManager.Instance.off(EVENT_ENUM.PLAYER_BORN,this.onChangeDirection )
    EventManager.Instance.off(EVENT_ENUM.PLAYER_MOVE_END,this.onChangeDirection)
    EventManager.Instance.off(EVENT_ENUM.ATTACK_ENENY,this.onDead)
  }

  onChangeDirection(isInit:boolean=false){
    if(this.state===ENTITY_STATE_ENUM.DEATH||!DataManager.Instance.player) return
    const {x:playerX,y:playerY}=DataManager.Instance.player
    const disX=playerX-this.x // 计算X轴差值
    const disY=playerY-this.y// 计算Y轴差值
    // if(!isInit) return
    if(disX>=0&&disY>0){
      this.direction=Math.abs(disX)>=Math.abs(disY)?DIRECTION_ENUM.RIGHT:DIRECTION_ENUM.BOTTOM
    }else if(disX>=0&&disY<=0){
      this.direction=Math.abs(disX)>=Math.abs(disY)?DIRECTION_ENUM.RIGHT:DIRECTION_ENUM.TOP
    }else if(disX<0&&disY>0){
      this.direction=Math.abs(disX)>=Math.abs(disY)?DIRECTION_ENUM.LEFT:DIRECTION_ENUM.BOTTOM
    }else if(disX<0&&disY<=0){
      this.direction=Math.abs(disX)>=Math.abs(disY)?DIRECTION_ENUM.LEFT:DIRECTION_ENUM.TOP
    }
  }

  onDead(id:string){
    console.log('被攻击id：'+id);
    if(this.state===ENTITY_STATE_ENUM.DEATH){
      return
    }
    if(this.id===id){
      this.state=ENTITY_STATE_ENUM.DEATH
    }
  }
}
